package com.ruoyi.dataSet.http;

import com.ruoyi.dataSet.DTO.DocumentSegmentCreateRequest;
import com.ruoyi.dataSet.DTO.DocumentSegmentUpdateRequest;
import okhttp3.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class HttpClientForSegment {

    private static final String API_URL = "http://127.0.0.1:88/v1";
    private static final String API_KEY = "dataset-K3u3beBG8fcO3ss4urRhdbwM";
    private static final OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(100, TimeUnit.SECONDS)
        .readTimeout(100, TimeUnit.SECONDS)
        .writeTimeout(100, TimeUnit.SECONDS)
        .build();

    // 创建文档分段
    public static String createSegment(String datasetId, String documentId, DocumentSegmentCreateRequest request) throws IOException {
        StringBuilder jsonBodyBuilder = new StringBuilder("{");

        if (request.getSegments() != null) {
            jsonBodyBuilder.append("\"segments\": ["); // 这里改成了数组格式
            // mode
            if (request.getSegments().getContent() != null && !request.getSegments().getContent().isEmpty()) {
                jsonBodyBuilder.append("{")
                    .append("\"content\": \"").append(request.getSegments().getContent()).append("\",");
                if (request.getSegments().getAnswer() != null && !request.getSegments().getAnswer().isEmpty()) {
                    jsonBodyBuilder.append("\"answer\": \"").append(request.getSegments().getAnswer()).append("\",");
                }

                if (request.getSegments().getKeywords() != null && !request.getSegments().getKeywords().isEmpty()) {
                    jsonBodyBuilder.append("\"keywords\": ").append(new ObjectMapper().writeValueAsString(request.getSegments().getKeywords())).append(",");
                    jsonBodyBuilder.deleteCharAt(jsonBodyBuilder.length() - 1); // 删除最后一个逗号
                }
                jsonBodyBuilder.append("},");
            }
            jsonBodyBuilder.deleteCharAt(jsonBodyBuilder.length() - 1); // 删除最后一个逗号
            jsonBodyBuilder.append("],");
        }

        // Remove the last comma if there is one
        if (jsonBodyBuilder.charAt(jsonBodyBuilder.length() - 1) == ',') {
            jsonBodyBuilder.deleteCharAt(jsonBodyBuilder.length() - 1);
        }

        jsonBodyBuilder.append("}");

        String jsonBody = jsonBodyBuilder.toString();
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);

        System.out.println("jsonBody: " + jsonBody);
        Request requestObj = new Request.Builder()
            .url(API_URL + "/datasets/" + datasetId + "/documents/" + documentId + "/segments")
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .post(body)
            .build();

        System.out.println("url:" + API_URL + "/datasets/" + datasetId + "/documents/" + documentId + "/segments");
        System.out.println("jsonBody: " + jsonBody);
        try (Response response = client.newCall(requestObj).execute()) {
            return response.body().string();
        }
    }


    // 获取文档分段
    public static String getSegments(String datasetId, String documentId, String page, String limit) throws IOException {
        HttpUrl url = HttpUrl.parse(API_URL + "/datasets/" + datasetId + "/documents/" + documentId + "/segments")
            .newBuilder()
            .addQueryParameter("page", page != null && !page.isEmpty() ? page : "1")
            .addQueryParameter("limit", limit != null && !limit.isEmpty() ? limit : "20")
            .build();

        Request request = new Request.Builder()
            .url(url)
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .get()
            .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }
    // 删除文档分段
    public static String deleteSegment(String datasetId, String documentId, String segmentId) throws IOException {
        Request request = new Request.Builder()
            .url(API_URL + "/datasets/" + datasetId + "/documents/" + documentId + "/segments/" + segmentId)
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .delete()
            .build();

        System.out.println("url:" + API_URL + "/datasets/" + datasetId + "/documents/" + documentId + "/segments/" + segmentId);
        try (Response response = client.newCall(request).execute()) {
            System.out.println("response: " + response);
            return response.body().string();
        }
    }

    // 更新文档分段
    public static String updateSegment(String datasetId, String documentId, String segmentId, DocumentSegmentUpdateRequest request) throws IOException {
        StringBuilder jsonBodyBuilder = new StringBuilder("{");

        if (request.getContent() != null && !request.getContent().isEmpty()) {
            jsonBodyBuilder.append("\"content\": \"").append(request.getContent()).append("\",");
        }

        if (request.getAnswer() != null && !request.getAnswer().isEmpty()) {
            jsonBodyBuilder.append("\"answer\": \"").append(request.getAnswer()).append("\",");
        }

        if (request.getKeywords() != null && !request.getKeywords().isEmpty()) {
            jsonBodyBuilder.append("\"keywords\": ").append(new ObjectMapper().writeValueAsString(request.getKeywords())).append(",");
        }

        if (request.getEnabled() != null) {
            jsonBodyBuilder.append("\"enabled\": ").append(request.getEnabled()).append(",");
        }

        if (request.getRegenerateChildChunks() != null) {
            jsonBodyBuilder.append("\"regenerate_child_chunks\": ").append(request.getRegenerateChildChunks()).append(",");
        }

        // Remove the last comma if there is one
        if (jsonBodyBuilder.charAt(jsonBodyBuilder.length() - 1) == ',') {
            jsonBodyBuilder.deleteCharAt(jsonBodyBuilder.length() - 1);
        }

        jsonBodyBuilder.append("}");

        String jsonBody = jsonBodyBuilder.toString();
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);

        Request requestObj = new Request.Builder()
            .url(API_URL + "/datasets/" + datasetId + "/documents/" + documentId + "/segments/" + segmentId)
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .post(body)
            .build();

        try (Response response = client.newCall(requestObj).execute()) {
            return response.body().string();
        }
    }
}
